<?php 
namespace App\Http\Components;

use App\Http\Components\AppComponent;

use DB;
use App\library\jpush\JPush;
use App\Models\OrderModel;
/**
* 
*/
class JpushComponent extends AppComponent{
	
	public function __construct(){
        parent::__construct();
	}

    /**
     * 获取容云api接口
     */
    public static function server(){
        app()->configure('account');
        $app_key = config('account.jpush_app_key');
        $app_secret = config('account.jpush_app_secret');
        return new JPush($app_key,$app_secret);
    }


    /**
     * 推送
     */
    public static function push($is_to_all = false,$user_list,$message,$desc,$link,$link_type = 'none',$order_id='',$l_id=''){
        $save_data = array();
        $server = SELF::server();
        //推送信息基础数据
        $new_data = array('message'=>$message,'desc'=>$desc);

        if(!$is_to_all){    //指定推送用户
            foreach($user_list AS $uitem){
                $new_data['user_id'] = $uitem;
                $save_data[] = $new_data;
            }
            DB::table('at_message_system_publish')->insert($save_data);
        }else{  //全部推送
            $user_list =  DB::table('user')->lists('user_id');

            foreach($user_list AS $uitem){
                $new_data['user_id'] = $uitem;
                $save_data[] = $new_data;
            }
            DB::table('at_message_system_publish')->insert($save_data);
        }

        $notification['alert'] = empty($message)?$desc:$message;

        if($link_type == 'href'){
            $extras = array('link'=>$link,'link_type'=>$link_type);
        }elseif($link_type == 'order'){

        }elseif($link_type == 'limit'){
            $extras = array('link_type'=>$link_type,'l_id'=>$l_id);
        }else{
            $extras = array('link_type'=>$link_type);
        }

        if($is_to_all){
            $push_result = $server->push()
                ->setPlatform('all')
                ->addAllAudience()
                ->addAndroidNotification($desc, $message, 1, $extras)
                ->addIosNotification($desc, 'iOS sound', JPush::DISABLE_BADGE, true, 'iOS category', $extras)
                ->setOptions(100000, 3600, null, false)
                ->send();
        }else{
            $push_result = $server->push()
                ->setPlatform('all')
                ->addAlias($user_list)
                ->addAndroidNotification($desc, $message, 1, $extras)
                ->addIosNotification($desc, 'iOS sound', JPush::DISABLE_BADGE, true, 'iOS category', $extras)
                ->setOptions(100000, 3600, null, false)
                ->send();
        }
        return $push_result;
    }

}
